package logic

import (
	"context"
	"fmt"
	"math/rand"
	"time"
	"work_1/models"
	"work_1/pkg"

	"work_1/shop_rpc/internal/svc"
	"work_1/shop_rpc/shop_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SmsCodeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSmsCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SmsCodeLogic {
	return &SmsCodeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SmsCodeLogic) SmsCode(in *shop_rpc.SmsCodeRequest) (*shop_rpc.SmsCodeResponse, error) {
	// todo: add your logic here and delete this line
	key := "code_phone:" + in.UserPhone
	rediskey := "rediskey_code_phone:" + in.UserPhone
	get_code, _ := models.Rdb.Get(models.Ctx, rediskey).Result()
	if get_code != "" {
		return nil, fmt.Errorf("一分钟内不得重发")
	}
	code := fmt.Sprintf("%d", rand.Intn(9000)+1000)
	captcha, err := pkg.SmsCaptcha(code)
	if err != nil {
		return nil, err
	}
	if *captcha.Body.Code != "OK" {
		return nil, fmt.Errorf(*captcha.Body.Message)
	}
	models.Rdb.Set(models.Ctx, key, code, 5*time.Minute)
	models.Rdb.Set(models.Ctx, rediskey, code, 1*time.Minute)
	return &shop_rpc.SmsCodeResponse{}, nil
}
